package com.sproutcat.sample.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author tzg
 */
@Configuration
@Slf4j
public class RabbitConfig {

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            log.debug("ConfirmCallback:     相关数据： {}", correlationData);
            log.debug("ConfirmCallback:     确认情况： {}", ack);
            log.debug("ConfirmCallback:     原因： {}", cause);
        });

        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.debug("ReturnCallback:     消息： {}", message);
            log.debug("ReturnCallback:     回应码： {}", replyCode);
            log.debug("ReturnCallback:     回应信息： {}", replyText);
            log.debug("ReturnCallback:     交换机： {}", exchange);
            log.debug("ReturnCallback:     路由键： {}", routingKey);
        });

        return rabbitTemplate;
    }

}
